package controller;

import beans.AlgorithmDetail;
import beans.Category;
import beans.LogEnum;
import beans.Model;
import dao.*;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import portal.controller.BaseServlet;
import utils.LogOperateEnum;
import utils.LogUtil;
import utils.UserLogUtil;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Servlet implementation class AlgorithmServlet
 */
public class ModelServlet extends BaseServlet {
    private static final long serialVersionUID = 1L;
    private static ModelDao modelDao;
    @Autowired
    AlgorithmDao algorithmDao ;
    @Autowired
    PublicDao publicDao;
    //private static UserDao userDao = new UserDao();

    /**
     * @see HttpServlet#HttpServlet()
     */
    public ModelServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    /**ns
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//    	Enumeration<String> em = request.getParameterNames();
//    	while(em.hasMoreElements()){
//    		String name = em.nextElement();
//    		System.out.println(name + ": " + request.getParameter(name));
//    	}

        JSONObject dataJson = JSONObject.fromObject(request.getParameter("data"));
        String operateType = request.getParameter("operateType");
        modelDao = new ModelDao();
        switch (operateType) {
            case "showAll":
                doShowAll(request, response, dataJson);
                break;
            case "addModel":
                doAddModel(request, response, dataJson);
                break;
            case "showDetail":
                doShowDetail(request, response, dataJson);
                break;
            case "alterModel":
                doAlterModel(request, response, dataJson);
                break;
            case "deleteModel":
                doDeleteModel(request, response, dataJson);
            default:
                break;
            case "configModel":
            	configModel(request,response,dataJson);
            	break;
            case "categoryList":
            	categoryList(request,response);
            	break;
            case "preview":
                preview(request,response);
                break;
            case "allmodelNum":
            	doGetAllmodelNum(request,response);
            	break;
        }
    }

    private void preview(HttpServletRequest request, HttpServletResponse response) throws IOException {
        JSONObject result = new JSONObject();
        try {
            String user = (String) request.getSession().getAttribute("userId");
//            System.out.println("request.getParameter(start):"+request.getParameter("start"));
            JSONArray startArray = JSONArray.fromObject(request.getParameter("start"));
//            System.out.println("startArray.toString():"+startArray.toString());
            JSONArray endArray = JSONArray.fromObject(request.getParameter("end"));
//            System.out.println("request.getParameter(end):"+request.getParameter("end"));
            result = new JSONObject();
            result.put("start",publicDao.packAlgorithmDetail(startArray,user));
            result.put("end",publicDao.packAlgorithmDetail(endArray,user));
//            System.out.println("result.toString():"+result.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        response.getWriter().print(result.toString());
    }



    private void categoryList(HttpServletRequest request, HttpServletResponse response) throws IOException {
		List<Object> algorithms = algorithmDao.allAlgorithmInCategory();
		JSONObject result = new JSONObject();
		CategoryDao categoryDao  = new CategoryDao();
		List<Object> categorys = categoryDao.categoryWithAlgorithm();
		Map<String, String> categoryMap = new HashMap<>();
		
		JSONArray categoryArray = new JSONArray();
		JSONArray algorithmArray = new JSONArray();
		for(Object a:categorys){
			Category aa = (Category)a;
			categoryMap.put(aa.getCategoryId()+"",aa.getCategoryName());
			JSONObject one = new JSONObject();
			one.put("categoryId", aa.getCategoryId());
			one.put("categoryName", aa.getCategoryName());
			categoryArray.add(one);
		}
		result.put("category", categoryArray);
		for(Object a:algorithms){
			AlgorithmDetail algorithm = (AlgorithmDetail)a;
			JSONObject one = new JSONObject();
			one.put("algorithmId", algorithm.getId());
			one.put("algorithmName", algorithm.getName());
			one.put("categoryId", algorithm.getFunction().getCategoryId()+","+algorithm.getType().getCategoryId());
			one.put("paramNum", algorithm.getParamsCount());
			algorithmArray.add(one);
		}
		result.put("algorithm", algorithmArray);
		response.getWriter().print(result.toString());
		
		
	}

	/**
     * 配置算法组件通信  By李金鑫
     * @param request
     * @param response
     * @param dataJson
     * @throws IOException
     * @throws ParseException
     */
     private void configModel(HttpServletRequest request, HttpServletResponse response, JSONObject dataJson) throws IOException {
		// TODO 自动生成的方法存根
    	//获取userId
        String user = (String) request.getSession().getAttribute("userId");
        //获取json
        String currentAlgorithmId = dataJson.getString("currentAlgorithmId");
        JSONArray frontAlgorithmIds = dataJson.getJSONArray("frontAlgorithmIds");
        String currentBlockId=dataJson.getString("currentBlockId");
        AlgorithmDetail currentAlgorithmDetail = new AlgorithmDetail();
        if(!(currentAlgorithmId.equals("")||currentAlgorithmId==null)){
        	currentAlgorithmDetail = algorithmDao.getAlgorithmDetail(currentAlgorithmId,user);
        }        	
        JSONObject result = new JSONObject();
        JSONObject currentAlgorithm=JSONObject.fromObject(currentAlgorithmDetail);
        currentAlgorithm.put("blockId",currentBlockId);
        result.put("currentAlgorithmDetail", currentAlgorithm);
        JSONArray frontAlgorithm=new JSONArray();
        JSONObject temp = frontAlgorithmIds.getJSONObject(0);
        String resultString = "";
        if(!temp.get("blockId").equals("uiStart_1")){
        	for (int i = 0; i < frontAlgorithmIds.size(); i++) {
        		JSONObject frontAlgorithmId = frontAlgorithmIds.getJSONObject(i);
        		String blockId=frontAlgorithmId.getString("blockId");
        		if(blockId.indexOf("uiData")>-1){
        		    resultString = frontAlgorithmId.getString("blockId");
                }else{
                    String frontId=frontAlgorithmId.getString("algorithmId");
                    AlgorithmDetail frontAlgorithmDetail = algorithmDao.getAlgorithmDetail(frontId,user);
                    JSONObject algorithmObject = JSONObject.fromObject(frontAlgorithmDetail);
                    if(algorithmObject.toString()!=null){
                        algorithmObject.put("blockId",blockId);
                        algorithmObject.put("blockName",frontAlgorithmId.getString("blockName"));
                    }else{
                        algorithmObject.put("blockId","");
                        algorithmObject.put("blockName","");
                    }
                    frontAlgorithm.add(algorithmObject);
                }
            }
        	result.put("frontAlgorithmDetails", frontAlgorithm);

        }
        if(currentAlgorithmId.equals("")||currentAlgorithmId==null){
        	
        }
        
        //打印日志
        String conclusion ="配置算法:"+currentAlgorithmId+",模块："+currentBlockId+"组件通信";
        LogUtil.log(user,LogOperateEnum.configModel,conclusion);
         result.put("blockId",resultString);
         response.getWriter().print(result.toString());
	}

	/**
     * 显示全部模型
     * @param request
     * @param response
     * @param dataJson
     * @throws IOException
     */
    private void doShowAll(HttpServletRequest request, HttpServletResponse response, JSONObject dataJson) throws IOException {
        //获取userId
        String user = (String) request.getSession().getAttribute("userId");
        //获取json
        Integer onePageCount = Integer.parseInt(request.getParameter("onePageCount"));
        Integer currentPage = Integer.parseInt(request.getParameter("currentPage"));
        List<Object> algorithms = modelDao.getModels(onePageCount, currentPage);
        int pagenum = modelDao.getModelPageNum(onePageCount);
        JSONObject result = new JSONObject();
        JSONObject content = new JSONObject();
        content.put("models", JSONArray.fromObject(algorithms));
        content.put("pageNum", pagenum);
        result.put("result", content);
        //打印日志
        String conclusion = "查询所有模型详细信息";
        LogUtil.log(user,LogOperateEnum.showDetailModel,conclusion);
        //返回json
        response.getWriter().print(result.toString());
    }

    /**
     * 添加模型方法  By尹行
     * @param request
     * @param response
     * @param dataJson
     * @throws IOException
     * @throws ParseException
     */
    private void doAddModel(HttpServletRequest request, HttpServletResponse response, JSONObject dataJson) throws IOException {
    	
        //获取userId
        String userId = (String) request.getSession().getAttribute("userId");
        //获取json结果
        String name = dataJson.getString("name");
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String  createTime = df.format(new Date());
        Integer nesting = Integer.parseInt(dataJson.getString("isNesting"));
        String nestJson = dataJson.getString("nestJson");
        String json = dataJson.getString("json");
//        Integer is_reuse = Integer.parseInt(dataJson.getString("isReuse"));
        Integer reuse = 0;
        String introduction = dataJson.getString("introduction");
        Integer modelId = -1;
        //返回结果
        Boolean res = false;
        List<Object> results =  modelDao.addModelReturnId(name,userId,createTime,nesting,nestJson,json,reuse,introduction,0);
        if (results.size() > 0) {
            res = true;
            modelId = (int) results.get(0);
        }
        JSONObject result = new JSONObject();
        result.put("modelId", modelId);
        result.put("result", res);
        response.getWriter().print(result.toString());
        // 日志记录
        UserLogUtil.dbLog(LogEnum.model, LogEnum.add,
                userId, LogEnum.model.getValue()+"编号："+modelId+"，名称："+name);
    }

    /**
     * 查询模型信息   By李金鑫
     * @param request
     * @param response
     * @param dataJson
     * @throws IOException
     */
    private void doShowDetail(HttpServletRequest request, HttpServletResponse response, JSONObject dataJson) throws IOException {
        // TODO Auto-generated method stub
        //获取userId
        String user = (String) request.getSession().getAttribute("userId");
        //获取模型id
    	String modelId = request.getParameter("modelId");
    	//获取结果
    	List<Object> model=modelDao.getModelByModelId(modelId);
        JSONObject result = new JSONObject();
        result.put("result", JSONArray.fromObject(model));
		//返回json
        response.getWriter().print(result.toString());
    }

    /**
     * 修改模型    By尹行
     * @param request
     * @param response
     * @param dataJson
     */
    private void doAlterModel(HttpServletRequest request, HttpServletResponse response, JSONObject dataJson) throws IOException {
        //获取userId
        String userId = (String) request.getSession().getAttribute("userId");
        //获取json内容
        String model_id = dataJson.getString("modelId");
        String name = dataJson.getString("name");
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String  create_time = df.format(new Date());
        Integer is_nesting = Integer.parseInt(dataJson.getString("isNesting"));
        String nest_json = dataJson.getString("nestJson");
        String json = dataJson.getString("json");
        Integer is_reuse = Integer.parseInt(dataJson.getString("isReuse"));
        String introduction = dataJson.getString("introduction");
        //获取旧结果集，用于之后对比
        List<Object> list = modelDao.getModelByModelId(model_id);
        Model mod = (Model)list.get(0);
        //获取结果
        Boolean res = modelDao.alterModel(model_id,name,userId,create_time,is_nesting,nest_json,json,is_reuse,introduction);
        String back = res?"true":"false";
        JSONObject result = new JSONObject();
        result.put("result", back);
        //返回json
        response.getWriter().print(result.toString());
        // 日志记录
        UserLogUtil.dbLog(LogEnum.model, LogEnum.update,
                userId, LogEnum.model.getValue()+"编号："+model_id);
    }

    /**
     * 删除模型方法  By尹行
     * @param request
     * @param response
     * @param dataJson
     * @throws IOException
     */
    private void doDeleteModel(HttpServletRequest request, HttpServletResponse response, JSONObject dataJson) throws IOException {
        //获取userId
        String userId = (String) request.getSession().getAttribute("userId");
        //获取要删除的模型和id
        String model_id = request.getParameter("modelId");
      //获取要删除的模型信息
        List<Object> list = modelDao.getModelByModelId(model_id);
        JSONObject result = new JSONObject();
        if (list.size()>0) {
			Model mod = (Model) list.get(0); //获取模型名字
			//获取结果
			Boolean res = modelDao.deleteModel(model_id);
			String back = res ? "true" : "false";
			result.put("result", back);
			//返回json
			response.getWriter().print(result.toString());
            // 日志记录
            UserLogUtil.dbLog(LogEnum.model, LogEnum.delete,
                    userId, LogEnum.model.getValue()+"编号："+model_id+"，名称："+mod.getName());
		}else{
			result.put("result", "false");
			response.getWriter().print(result.toString());
		}
    }
    //获取所有模型数量
    private void doGetAllmodelNum(HttpServletRequest request, HttpServletResponse response) throws IOException {
        HttpSession session = request.getSession();
//		String algorithmName = algorithmDao.getAlgorithmDetail(algorithmId, userId).getName();
        JSONObject result = new JSONObject();
        int modelNum = modelDao.modelNum();
        result.put("result", modelNum);
        response.getWriter().print(result.toString());
    }
}
